const Router = require("@koa/router");
const { PrismaClient } = require("@prisma/client");

const router = new Router({ prefix: "/habits" });
const prisma = new PrismaClient();

// 查询某一天的 habits 记录
router.get('/on-date', async (ctx) => {
  try {
    const { date, userId } = ctx.query;
    if (!date || !userId) {
      ctx.status = 400;
      ctx.body = { success: false, message: 'date 和 userId 为必传参数' };
      return;
    }

    // 验证 userId 是否为有效整数
    const userIdInt = parseInt(userId, 10);
    if (isNaN(userIdInt)) {
      ctx.status = 400;
      ctx.body = { success: false, message: 'userId 必须是有效的整数' };
      return;
    }

    // 验证 date 格式 (YYYY-MM-DD)
    // 正则表达式确保日期格式为 YYYY-MM-DD
    if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {
      ctx.status = 400;
      ctx.body = { success: false, message: 'date 参数格式必须是 YYYY-MM-DD' };
      return;
    }

    // 将日期字符串转换为当天的开始和结束时间戳 (毫秒)
    // 传入的 date 是东八区时间 (YYYY-MM-DD)
    // 构造东八区的起始时间字符串
    const dayStartStr = `${date}T00:00:00.000+08:00`;
    // 构造东八区的结束时间字符串
    const dayEndStr = `${date}T23:59:59.999+08:00`;

    const dayStart = new Date(dayStartStr);
    const dayEnd = new Date(dayEndStr);

    // 检查日期转换是否成功
    if (isNaN(dayStart.getTime()) || isNaN(dayEnd.getTime())) {
      ctx.status = 400;
      ctx.body = { success: false, message: '无效的日期值，无法进行转换' };
      return;
    }

    // 将毫秒转换为秒
    const startTime = Math.floor(dayStart.getTime() / 1000);
    const endTime = Math.floor(dayEnd.getTime() / 1000);

    const habits = await prisma.habits.findMany({
      where: {
        user_id: userIdInt,
        create_at: {
          gte: startTime,
          lte: endTime,
        },
      },
    });

    ctx.body = { success: true, data: habits };
  } catch (err) {
    console.error('查询每日 habits 失败:', err);
    ctx.status = 500;
    ctx.body = { success: false, message: err.message };
  }
});

// 获取某个时间段的 habits
router.get("/", async (ctx) => {
  try {
    const { startTime, endTime, userId } = ctx.query;
    if (!startTime || !endTime || !userId) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: "startTime、endTime和userId为必传参数",
      };
      return;
    }
    const startTimeInt = parseInt(startTime, 10);
    const endTimeInt = parseInt(endTime, 10);
    const userIdInt = parseInt(userId, 10);
    if (isNaN(startTimeInt) || isNaN(endTimeInt) || isNaN(userIdInt)) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: "startTime、endTime和userId必须是有效的整数",
      };
      return;
    }
    const habits = await prisma.habits.findMany({
      where: {
        create_at: {
          gte: startTimeInt,
          lte: endTimeInt,
        },
        user_id: userIdInt,
      },
      orderBy: {
        create_at: "desc",
      },
    });
    ctx.body = { success: true, data: habits };
  } catch (err) {
    console.error("获取所有 habits 失败:", err);
    ctx.status = 500;
    ctx.body = { success: false, message: err.message };
  }
});

// 根据 ID 获取单个 habit
router.get("/:id", async (ctx) => {
  try {
    const id = parseInt(ctx.params.id, 10);
    if (isNaN(id)) {
      ctx.status = 400;
      ctx.body = { success: false, message: "ID 必须是有效的整数" };
      return;
    }
    const habit = await prisma.habits.findUnique({
      where: { id },
    });
    if (habit) {
      ctx.body = { success: true, data: habit };
    } else {
      ctx.status = 404;
      ctx.body = { success: false, message: "Habit not found" };
    }
  } catch (err) {
    console.error("获取 habit 失败:", err);
    ctx.status = 500;
    ctx.body = { success: false, message: err.message };
  }
});

// 创建 habit 【注意：create_at是时间戳(秒)】
router.post("/", async (ctx) => {
  try {
    const { remark, image_urls, score, user_id, create_at, type } =
      ctx.request.body;

    // 计算当天的起止时间戳
    const date = new Date(create_at * 1000);
    const startOfDay = Math.floor(
      new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() /
      1000
    );
    const endOfDay = startOfDay + 24 * 60 * 60 - 1;

    // 检查当天是否已存在同类型的 habit
    const existingHabit = await prisma.habits.findFirst({
      where: {
        user_id,
        type,
        create_at: {
          gte: startOfDay,
          lte: endOfDay,
        },
      },
    });

    if (existingHabit) {
      ctx.status = 400;
      ctx.body = { success: false, message: "当天已存在同类型的 habit" };
      return;
    }

    const habit = await prisma.habits.create({
      data: { remark, image_urls, score, user_id, create_at, type },
    });
    ctx.body = { success: true, data: habit };
  } catch (err) {
    console.error("创建 habit 失败:", err);
    ctx.status = 500;
    ctx.body = { success: false, message: err.message };
  }
});

// 更新 habit
router.put("/:id", async (ctx) => {
  try {
    const id = parseInt(ctx.params.id, 10);
    if (isNaN(id)) {
      ctx.status = 400;
      ctx.body = { success: false, message: "ID 必须是有效的整数" };
      return;
    }
    const { remark, image_urls, score, user_id, create_at, type } =
      ctx.request.body;
    const habit = await prisma.habits.update({
      where: { id },
      data: { remark, image_urls, score, user_id, create_at, type },
    });
    ctx.body = { success: true, data: habit };
  } catch (err) {
    console.error("更新 habit 失败:", err);
    ctx.status = 500;
    ctx.body = { success: false, message: err.message };
  }
});

// 删除 habit
router.delete("/:id", async (ctx) => {
  try {
    const id = parseInt(ctx.params.id, 10);
    if (isNaN(id)) {
      ctx.status = 400;
      ctx.body = { success: false, message: "ID 必须是有效的整数" };
      return;
    }
    await prisma.habits.delete({ where: { id } });
    ctx.body = { success: true };
  } catch (err) {
    console.error("删除 habit 失败:", err);
    ctx.status = 500;
    ctx.body = { success: false, message: err.message };
  }
});

module.exports = router;
